package demo4;

import java.util.Scanner;

public class NQueens {
    private int[] x; // x[i] 表示第 i 行皇后的列位置
    private int n;    // 棋盘大小
    private int solutionCount; // 解的计数

    public NQueens(int n) {
        this.n = n;
        this.x = new int[n];
        this.solutionCount = 0;
    }

    // 检查在第 k 行放置皇后是否合法
    private boolean canPlace(int k) {
        for (int i = 0; i < k; i++) {
            // 检查是否在同一列或同一斜线
            if (x[i] == x[k] || Math.abs(x[i] - x[k]) == Math.abs(i - k)) {
                return false;
            }
        }
        return true;
    }

    // 回溯法求解
    private void dfa(int k) {
        if (k == n) {
            solutionCount++;
            System.out.println("解 " + solutionCount + ":");
            printSolution();
            return;
        }
        for (int j = 0; j < n; j++) {
            x[k] = j; // 将皇后放在第 k 行的第 j 列
            if (canPlace(k)) {
                dfa(k + 1);
            }
        }
    }


    private void printSolution() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (x[i] == j) {
                    System.out.print("Q ");
                } else {
                    System.out.print(". ");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    public void solve() {
        if (n < 1) {
            System.out.println("无效的输入，n 必须大于 0");
            return;
        }
        dfa(0);
        if (solutionCount == 0) {
            System.out.println("无解");
        } else {
            System.out.println("共找到 " + solutionCount + " 个解");
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入皇后个数 n: ");
        int n = scanner.nextInt();
        NQueens nQueens = new NQueens(n);
        nQueens.solve();
        scanner.close();
    }
}
